﻿using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using StockLib.Data;

namespace StockLib.Quote
{
    public partial class StockReceiver
    {

        /// <summary>
        /// 接收到新闻文本文件
        /// </summary>
        /// <param name="tsdata">通视数据</param>
        private void ReceiveFileNews(ref ReceiveData tsdata)
        {
            Stock stock = new Stock();
            FileStream fileStream = null;
            FileInfo fileInfo = null;

            try
            {
                fileInfo = new FileInfo(NewsDataFile.Instance.GetFileName(tsdata.m_szFileName));
                if (!fileInfo.Directory.Exists)
                    Directory.CreateDirectory(fileInfo.Directory.FullName);
                fileStream = new FileStream(fileInfo.FullName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

                byte[] buffer = new byte[tsdata.m_dwLen];
                Marshal.Copy(tsdata.m_pData, buffer, 0, buffer.Length);
                fileStream.Write(buffer, 0, buffer.Length);

                // 通知新闻资讯数据接收
                OnDataChanged(this, new ReceiverDataEventArgs(DataType.News));
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("文件操作出错 股票代码:{0} 异常信息:{1}", stock.Code, ex.ToString()));
                throw ex;
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream.Dispose();
                    fileStream = null;
                }
            }
        }
    }
}
